<template>
	<view class="lease-bill">
		<!-- Header -->
		<view class="container total-panel">
			<view class="total-box">
				<view class="total-item">
					<view class="total-title">剩余待还金额(元)</view>
					<view class="total-count">{{ amount.returned }}</view>
				</view>
				<view class="total-item">
					<view class="total-title">已还金额(元)</view>
					<view class="total-count">{{ amount.repaid }}</view>
				</view>
			</view>
			<!-- <view class="total-panel-tips">还款日: 每月27日</view> -->
		</view>


		<!-- Navigatior -->
		<view class="container tabs">
			<block v-for="(item, index) in tabs" :key="index">
				<view class="tabs-item" :class="{'tabs-item--active': tabCurrent === index}" @tap="tabCurrent = index">
					{{ item.name }}
				</view>
			</block>
		</view>


		<!-- Tabs Content -->

		<!-- 待还款 -->
		<view v-show="tabCurrent === 0" class="tabs-content">
			<scroll-view class="scroll-view" scroll-y="true">
				<view class="bill-list">
					<u-checkbox-group @change="checkboxGroupChangeReturned" style="width: 100%;">
						<block v-for="(item, index) in returnedList" :key="item.id">
							<!-- <view class="bill row" @tap="returnedList[index].checked = !item.checked"> -->
							<!-- <view class="bill row" @tap="item.checked = true"> -->
							<view class="bill row" @tap="onCheckbox(index)">

								<u-checkbox :name="item.id" v-model="item.checked" shape="circle" />

								<view class="flex1">
									<view class="bill-content">
										<!-- Name -->
										<view class="bill-name normal">
											<!-- 本期 -->
											<!-- <view class="bill-sign-period">本期</view> -->
											<!-- 续租 -->
											<template v-if="item.is_relet * 1">
												<view class="bill-sign-extend">续</view>
											</template>
											<!-- 名称 -->
											{{ item.name }}
										</view>
										<!-- Price -->
										<view class="bill-price">
											<price color="#333333" :content="item.amount_payable + item.late_fee"
												mainSize="36rpx" minorSize="24rpx" :isSuffix="false" :isPrefix="true" />
										</view>
									</view>
									<view class="bill-widget">
										<view class="bill-widget-item">
											<view>本期应还</view>
											<view>￥{{ item.amount_payable || '0.00' }}</view>
										</view>
										<template v-if="item.late_fee * 1">
											<view class="bill-widget-item">
												<view>
													<text>滞纳金</text>
													<text class="ornament ml10">(逾期未还)</text>
												</view>
												<view>￥{{ item.late_fee || '0.00' }}</view>
											</view>
										</template>
										<!-- Time -->
										<view class="bill-widget-item">
											{{ item.repayment_time }} 至 {{ item.expire_time }}
										</view>
									</view>
								</view>
							</view>
						</block>
						<template v-if="!returnedList.length">
							<view class="empty-text">暂无待还账单~</view>
						</template>
					</u-checkbox-group>
				</view>
			</scroll-view>

			<view class="widget row">
				<!-- 				<u-checkbox v-model="isCheckedAllReturned" shape="circle" @change="checkedAllReturned">
					<text class="muted">全选</text>
				</u-checkbox> -->
				<view>
					<text>合计:</text>
					<price :content="countPrice" mainSize="38rpx" minorSize="30rpx" :isSuffix="false"
						:isPrefix="true" />
				</view>

				<view class="button-refund" style="width: 264rpx; margin-left: auto;" @tap="onReturnBill">还款</view>
			</view>
		</view>

		<!-- 待处理 -->
		<view v-show="tabCurrent === 2" class="tabs-content">
			<scroll-view class="scroll-view" scroll-y="true">
				<view class="bill-list">

					<block v-for="(item, index) in pendingList" :key="item.id">
						<!-- <view class="bill row" @tap="returnedList[index].checked = !item.checked"> -->
						<!-- <view class="bill row" @tap="item.checked = true"> -->
						<view class="bill row" @tap="onCheckbox(index)">

							<view class="flex1">
								<view class="bill-content">
									<!-- Name -->
									<view class="bill-name normal">
										<!-- 本期 -->
										<!-- <view class="bill-sign-period">本期</view> -->
										<!-- 续租 -->
										<template v-if="item.is_relet * 1">
											<view class="bill-sign-extend">续</view>
										</template>
										<!-- 名称 -->
										{{ item.name }}
									</view>
									<!-- Price -->
									<view class="bill-price">
										<price color="#333333" :content="item.amount_payable + item.late_fee"
											mainSize="36rpx" minorSize="24rpx" :isSuffix="false" :isPrefix="true" />
									</view>
								</view>
								<view class="bill-widget">
									<view class="bill-widget-item">
										<view>本期应还</view>
										<view>￥{{ item.amount_payable || '0.00' }}</view>
									</view>
									<template v-if="item.late_fee * 1">
										<view class="bill-widget-item">
											<view>
												<text>滞纳金</text>
												<text class="ornament ml10">(逾期未还)</text>
											</view>
											<view>￥{{ item.late_fee || '0.00' }}</view>
										</view>
									</template>
									<!-- Time -->
									<view class="bill-widget-item">
										{{ item.repayment_time }} 至 {{ item.expire_time }}
									</view>
								</view>
							</view>
						</view>
					</block>
					<template v-if="!returnedList.length">
						<view class="empty-text">暂无待还账单~</view>
					</template>

				</view>
			</scroll-view>


		</view>



		<!-- 已还款 -->
		<view v-show="tabCurrent === 1" class="tabs-content">
			<scroll-view class="scroll-view" scroll-y="true">
				<view class="bill-list">
					<block v-for="item in repaidList" :key="item.id">
						<view class="bill row">
							<view class="flex1">
								<view class="bill-content">
									<!-- Name -->
									<view class="bill-name normal muted">
										<!-- 续租 -->
										<template v-if="item.is_relet * 1">
											<view class="bill-sign-extend">续</view>
										</template>
										<!-- 名称 -->
										{{ item.name }}
									</view>
									<!-- Price -->
									<view class="bill-price">
										<price color="#999999" :content="item.amount_payable + item.late_fee"
											mainSize="36rpx" minorSize="24rpx" :isSuffix="false" :isPrefix="true" />
									</view>
								</view>
								<view class="bill-widget">
									<view class="bill-widget-item">
										<view>本期应还</view>
										<view>￥{{ item.amount_payable || '0.00' }}</view>
									</view>
									<template v-if="item.late_fee * 1">
										<view class="bill-widget-item">
											<view>
												<text>滞纳金</text>
												<text class="ornament ml10">(逾期未还)</text>
											</view>
											<view>￥{{ item.late_fee || '0.00' }}</view>
										</view>
									</template>
									<!-- Time -->
									<view class="bill-widget-item">
										<text>{{ item.repayment_time }} 至 {{ item.expire_time }}</text>
										<text style="color: #01D171;">已还清</text>
									</view>
								</view>
							</view>
						</view>
					</block>
					<template v-if="!repaidList.length">
						<view class="empty-text">暂无已还记录~</view>
					</template>
				</view>
			</scroll-view>

			<view class="widget">
				<view class="button-refund" style="opacity: .3;">还款</view>
			</view>
		</view>


		<!-- 支付方式 Popup -->
		<u-popup v-model="isPaywayPopup" mode="bottom" border-radius="20">
			<view class="payway">
				<view class="payway-title">选择支付方式</view>
				<view class="payway-list">
					<block v-for="item in paywayList" :key="item.id">
						<view class="payway-item" @tap="onPay(item.pay_way)">
							<u-icon :name="item.icon" width="48" height="48" />
							<view class="ml20">
								<view class="payway-name">{{ item.name }}</view>
								<view class="payway-extra">{{ item.extra }}</view>
							</view>
						</view>
					</block>
				</view>
				<view class="payway-cancel" @tap="isPaywayPopup = false">取消</view>
			</view>
		</u-popup>

		<!-- 支付密码 -->
		<set-pay-pwd ref="setPayPwd" @confirm="handlePayBill" />

	</view>
</template>


<script>
	import {
		getPayway,
		prepayment,
		getAlipayPayStatus
	} from '@/api/app';

	import {
		wxpay,
		alipay
	} from '@/utils/pay';
	import {
		repaymentBill
	} from '@/api/lease';

	export default {
		data() {
			return {
				orderID: '', // 租赁订单ID
				tabCurrent: 0, // tabs当前索引
				// tabs列表(样式宽度已固定，仅支持2个,需要添加请自行修改)
				tabs: [{
						key: 'returned',
						name: '待还款'
					},
					{
						kay: 'repaid',
						name: '已还款'
					},
					// {
					// 	kay: 'pending',
					// 	name: '待处理'
					// },
				],

				// 统计数据
				amount: {
					repaid: 0, // 应还金额
					returned: 0, // 待还金额
				},
				// repayableList: [],			// 应还款 数据列表
				returnedList: [], // 待还款 数据列表
				repaidList: [], // 已还款 数据列表

				// isCheckedAllReturned: false, // 待还款全选
				checkedAllReturnedList: [], // 已选中的待还款账单

				isPaywayPopup: false, // 支付方式 Popup
				paywayList: [], // 支付方式 数据列表
				payway: '', // 当前选择的支付方式

				countPrice: 0, // 合计还款
			}
		},

		methods: {
			// 获取数据并初始化
			initData() {
				// 获取待还款数据列表
				this.getReturned();
				// // 获取处理中数据列表
				// 	this.getPending();
				// 获取已还款数据列表
				this.getRepaid();
			},

			// 获取待还款数据列表
			getReturned() {
				repaymentBill({
					id: this.orderID,
					type: 'returned',
					action: 'info'
				}).then(res => {
					const data = res.data;
					this.$set(this.amount, 'repaid', data.amount_repaid);
					this.$set(this.amount, 'returned', data.amount_returned);

					const list = [];
					data.bill_list.map(item => list.push(Object.assign({}, item, {
						checked: false
					})));
					this.returnedList = list;
				});
			},

			// 获取待还款数据列表
			getPending() {
				repaymentBill({
					id: this.orderID,
					type: 'pending',
					action: 'info'
				}).then(res => {
					const data = res.data;
					this.$set(this.amount, 'repaid', data.amount_repaid);
					this.$set(this.amount, 'returned', data.amount_returned);

					const list = [];
					data.bill_list.map(item => list.push(Object.assign({}, item, {
						checked: false
					})));
					this.pendingList = list;
				});
			},

			// 获取已还款数据列表
			getRepaid() {
				repaymentBill({
					id: this.orderID,
					type: 'repaid',
					action: 'info'
				}).then(res => {
					const data = res.data;

					this.$set(this.amount, 'repaid', data.amount_repaid);
					this.$set(this.amount, 'returned', data.amount_returned);
					this.repaidList = data.bill_list;
				});
			},

			// onCheckbox(index) {
			// 	console.log(index, '546564564456564')
			// 	this.returnedList[index].checked = !this.returnedList[index].checked;
			// 	const checkedReturnedList = '';
			// 	this.returnedList.forEach(item => item.checked ? (checkedReturnedList = item.id) : '');
			// 	console.log(checkedReturnedList, '8789897897')
			// },

			onCheckbox(index) {
				// 先清空所有选中状态
				this.returnedList.forEach(item => {
					item.checked = false
				})

				// 只选中当前点击的
				this.returnedList[index].checked = true

				// 拿到选中的id
				let checkedReturnedId = []
				checkedReturnedId = [this.returnedList[index].id]
				
				this.checkboxGroupChangeReturned(checkedReturnedId);
			},

			// 待还款 选中任一checkbox时触发
			checkboxGroupChangeReturned(e) {
				this.checkedAllReturnedList = e;
				const isAllCheck = this.returnedList.find(item => item.checked == false);
				isAllCheck
					?
					this.isCheckedAllReturned = false :
					this.isCheckedAllReturned = true;
			},

			// 待还款全选
			// checkedAllReturned() {
			// 	if (this.isCheckedAllReturned) {
			// 		this.returnedList.map(val => val.checked = false);
			// 		this.checkedAllReturnedList = [];
			// 	} else {
			// 		const ids = [];
			// 		this.returnedList.map(val => {
			// 			ids.push(val.id);
			// 			val.checked = true;
			// 		});
			// 		this.checkedAllReturnedList = ids;
			// 	}
			// },

			// 支付
			handlePay(id, type) {

				// if(isOffline===true){
				// 		uni.showToast({
				// 			title: '提交成功',
				// 			icon: 'success'
				// 		});
				// 	return true;
				// }

				prepayment({
					from: type,
					order_id: id,
					repayment_id: this.checkedAllReturnedList[0]
				}).then(res => {
					const code = res.code;
					const data = res.data;

					switch (code) {
						case 1:
							this.handleWeCahtPay(data);
							break;
						case 10001:
							uni.showToast({
								title: '还款成功',
								icon: 'success'
							});
							break;
						case 20001:
							this.handleAlipayPay(data);
							break;
					}

					this.initData();
				});
			},

			// 微信支付
			handleWeCahtPay(data) {
				var that = this
				wxpay(data).then(res => {
					if (res == 'success') {
						uni.showToast({
							title: '还款成功',
							icon: 'success'
						});
						// 数据初始化
						that.initData();
					} else {
						uni.showToast({
							title: '还款失败',
							icon: 'none'
						});
					}
				})
			},

			// 支付宝支付
			handleAlipayPay(data) {
				// #ifdef H5
				alipay(data);
				// #endif

				// #ifdef MP-ALIPAY
				const tradeNo = data?.data?.trade_no;
				var _that = this
				my.tradePay({
					tradeNO: tradeNo,
					success: (res) => {
						var that = _that
						getAlipayPayStatus({
							trade_no: tradeNo
						}).then(res => {
							console.log(res)
							if (res.tradeStatus == 'TRADE_SUCCESS') {
								uni.showToast({
									title: '还款成功',
									icon: 'success'
								});
								// 数据初始化
								that.initData();
							} else {
								uni.showToast({
									title: '还款失败',
									icon: 'none'
								});
							}
						});
					},
					fail: (res) => {
						console.log(res);
						uni.showToast({
							title: '还款失败',
							icon: 'none'
						});
					}
				});
				// #endif
			},

			onReturnBill() {
				if (!this.checkedAllReturnedList.length) return this.$toast({
					title: '请选择账单'
				});
				this.isPaywayPopup = true;
			},

			// 选择支付方式
			onPay(payway) {
				console.log(this.payway, payway, "！2121212132")
				this.payway = payway;
				if (payway == 3) {
					this.$refs.setPayPwd.hasPayWord().then(res => {
						this.$refs.setPayPwd.showInputPwd();
					});
				} else {
					this.handlePayBill();
				}
				this.isPaywayPopup = false;
			},

			// 还款处理
			handlePayBill(password) {
				this.isPaywayPopup = false;
				const index = this.tabs[this.tabCurrent].key;

				let periodization = [];

				switch (index) {
					// 待还款
					case 'returned':
						periodization = this.checkedAllReturnedList;
						break;
				}
				this.$refs.setPayPwd.showConfirm = false;
				uni.showLoading({
					title: '支付中...',
					mask: true
				});
				repaymentBill({
					id: this.orderID,
					type: index,
					pay_way: this.payway,
					action: 'submit',
					pay_password: password,
					periodization_ids: periodization
				}).then(res => {
					const data = res.data;
					const id = data.order_id;
					const type = data.from;
					this.handlePay(id, type);
				}).catch(() => {
					uni.showToast({
						title: '支付失败',
						icon: 'none'
					})
				}).finally(() => {
					setTimeout(() => uni.hideLoading(), 500);
				});
			}
		},

		watch: {
			returnedList: {
				handler(list) {
					let price = 0;
					list.forEach(item => {
						if (item.checked) {
							const payable = item.amount_payable * 1;
							const latefee = item.late_fee * 1;
							price += payable + latefee;
						}
					})
					this.countPrice = price;
				},
				deep: true
			}
		},
		onShow() {
			// // 数据初始化
			// this.initData();
		},
		onLoad(options) {
			const index = options.index || 0;
			const id = options.id;
			this.orderID = id;
			this.tabCurrent = index;

			// 数据初始化
			this.initData();

			// 获取付款方式
			getPayway().then(res => {
				if (res.code != 1) return;
				const data = res.data;
				this.paywayList = data;
				console.log(data, "!212121488897897")
			});
		},
	}
</script>


<style scoped>
	.container {
		margin: 20rpx 20rpx 0 20rpx;
	}

	.lease-bill {
		display: flex;
		flex-direction: column;
		width: 100vw;
		height: 100vh;
		/* overflow: hidden; */
	}

	.total-panel {
		display: flex;
		flex-direction: column;
		justify-content: space-between;
		/* height: 256rpx; */
		height: 200rpx;
		padding: 30rpx 50rpx;
		border-radius: 10px;
		background-image: linear-gradient(90deg, #FF4D40, #3187FD);
		color: #FFFFFF;
	}

	.total-box {
		display: flex;
	}

	.total-item {
		flex: 1;
	}

	.total-title {
		font-size: 26rpx;
	}

	.total-count {
		font-size: 64rpx;
		font-weight: 500;
	}

	.total-panel-tips {
		font-size: 26rpx;
		color: #CEE5FF;
	}

	.tabs {
		display: flex;
		justify-content: space-between;
	}

	.tabs-item {
		display: flex;
		align-items: center;
		justify-content: center;
		width: 345rpx;
		height: 72rpx;
		border-radius: 2px;
		font-size: 28rpx;
		background-color: #FFFFFF;
		color: #333333;
	}

	.tabs-item--active {
		box-shadow: 0 0 0 1px #FF4D40;
		background-color: #E8F6FF;
		color: #FF4D40;
	}

	.tabs-content {
		position: relative;
		flex: 1;
		box-sizing: border-box;
		height: 100%;
		margin-top: 20rpx;
		overflow: hidden;
	}

	.scroll-view {
		height: calc(100% - 120rpx);
	}

	.bill-list {
		position: relative;
		padding: 0 20rpx;
		height: 100%;
	}

	.empty-text {
		position: absolute;
		top: 50%;
		left: 50%;
		transform: translate(-50%, -50%);
		color: #999999;
	}

	.bill {
		width: 100%;
		padding: 20rpx;
		border-radius: 7px;
		background-color: #FFFFFF;
	}

	.bill:nth-child(n+2) {
		margin-top: 20rpx;
	}

	.bill-content {
		display: flex;
		justify-content: space-between;
		width: 100%;
	}

	.bill-name {
		font-size: 28rpx;
		font-weight: 500;
	}

	.bill-sign-period,
	.bill-sign-extend {
		display: inline-block;
		box-sizing: border-box;
		padding: 2rpx 8rpx;
		margin-right: 10rpx;
		border-radius: 2px;
		font-size: 22rpx;
	}

	.bill-sign-period {
		border: 1px solid #FF4D40;
		color: #FF4D40;
	}

	.bill-sign-extend {
		border: 1px solid #01D171;
		color: #01D171;
	}

	.bill-price {
		text-align: right;
		min-width: 136rpx;
	}

	.bill-widget {
		font-size: 26rpx;
		color: #999999;
	}

	.bill-widget-item {
		display: flex;
		justify-content: space-between;
		margin-top: 10rpx;
	}

	.widget {
		display: flex;
		align-items: center;
		height: 120rpx;
		padding: 0 30rpx;
		background-color: #FFFFFF;
	}

	.button-refund {
		display: flex;
		align-items: center;
		justify-content: center;
		width: 100%;
		height: 84rpx;
		border-radius: 50px;
		font-size: 32rpx;
		background-color: #FF4D40;
		color: #FFFFFF;
	}

	.payway {
		/* border-radius: 6px 0; */
		/* background-color: #FFFFFF; */
		/* overflow: hidden; */
		/* background-color: #01D171; */
	}

	.payway-title {
		display: flex;
		align-items: center;
		justify-content: center;
		height: 100rpx;
		font-size: 30rpx;
		font-weight: 500;
		color: #333333;
	}

	.payway-list {
		padding: 20rpx 24rpx;
	}

	.payway-item {
		display: flex;
		align-items: center;
		height: 120rpx;
	}

	.payway-item:nth-child(n+2) {
		border-top: 1px solid #E5E5E5;
	}

	.payway-name {
		font-size: 28rpx;
		font-weight: 400;
		color: #101010;
	}

	.payway-extra {
		font-size: 24rpx;
		color: #999999;
	}

	.payway-cancel {
		display: flex;
		justify-content: center;
		align-items: center;
		height: 100rpx;
		font-size: 32rpx;
		background-color: #F6F6F6;
		color: #333333;
	}
</style>